import { createRouter, createWebHistory } from 'vue-router'
import { usePermissionStore } from '@/stores/permission'
import { ref } from 'vue'

// 基础路由配置
const constantRoutes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login/index.vue'),
        meta: { title: '登录' }
    },
    {
        path: '/test',
        name: 'Test',
        component: () => import('@/views/Test/index.vue'),
        meta: { title: '测试' }
    },
]

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes
})

// 用于记录是否已添加动态路由
const isAddDynamicRoutes = ref(false)

// 路由守卫
router.beforeEach(async (to, from, next) => {
    // 已添加动态路由则直接进入
    if (isAddDynamicRoutes.value) {
        next()
        return
    }

    if (to.path === '/login') {
        next()
        return
    }


    let token = localStorage.getItem('token')
    if (token) {
        // 已登录
        if (usePermissionStore().userPermissions.length === 0) {
            // 未获取权限
            await usePermissionStore().updateUserPermissions()
            isAddDynamicRoutes.value = true
            next(to.fullPath)
        } else {
            // 已获取权限
            isAddDynamicRoutes.value = true
            next(to.fullPath)
        }
    } else {
        // 未登录
        next('/login')
        return
    }
})

// 全局后置钩子
router.afterEach((to) => {
    document.title = to.meta?.title || '综合能源智慧管理'
})

export default router